﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Eniux.Windows.EnterpriseLibrary.Commands
{
    /// <summary>
    /// 附加命令
    /// </summary>
    public  class CommandSource //: FreezableCollection<CommandTrigger>, ICommandTrigger
    {
        #region 附加属性

        #region Triggers

        /// <summary>
        /// 获取给定依赖对象的附加属性Triggers的值
        /// </summary>
        /// <param name="source">依赖对象</param>
        /// <returns>附加属性Triggers的值</returns>
        public static ICommandTrigger GetTriggers(FrameworkElement source)
        {
            return (ICommandTrigger)source.GetValue(TriggersProperty);
        }

        /// <summary>
        /// 设置给定依赖对象的附加属性Triggers的值
        /// </summary>
        /// <param name="source">依赖对象</param>
        /// <param name="value">值</param>
        public static void SetTriggers(FrameworkElement source, ICommandTrigger value)
        {
            source.SetValue(TriggersProperty, value);
        }

        /// <summary>
        /// Trigger属性
        /// </summary>
        public static readonly DependencyProperty TriggersProperty =
            DependencyProperty.RegisterAttached(
                "Triggers",
                typeof(ICommandTrigger),
                typeof(CommandSource),
                new UIPropertyMetadata(
                    null,
                    OnTriggersPropertyChanged));

        private static void OnTriggersPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement element = d as FrameworkElement;

            ICommandTrigger commandTrigger = e.NewValue as ICommandTrigger;
            if (commandTrigger != null)
            {
                commandTrigger.Initialize(element);
            }
        }

        #endregion

        #endregion

        //private readonly HashSet<ICommandTrigger> _initList = new HashSet<ICommandTrigger>();

        //void ICommandTrigger.Initialize(FrameworkElement source)
        //{
        //    foreach (ICommandTrigger child in this)
        //    {
        //        if (!_initList.Contains(child))
        //        {
        //            InitializeCommandSource(source, child);
        //        }
        //    }
        //}

        //private void InitializeCommandSource(FrameworkElement source, ICommandTrigger child)
        //{
        //    child.Initialize(source);
        //    _initList.Add(child);
        //}
    }
}
